package org.geysermc.hydraulic.pack.modules;

import com.google.auto.service.AutoService;
import org.geysermc.hydraulic.Constants;
import org.geysermc.hydraulic.pack.PackModule;
import org.geysermc.hydraulic.pack.context.PackPostProcessContext;
import org.geysermc.hydraulic.util.PackUtil;
import org.geysermc.pack.bedrock.resource.manifest.Modules;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.UUID;

@AutoService(PackModule.class)
public class MetadataPackModule extends PackModule<MetadataPackModule> {
    public MetadataPackModule() {
        this.postProcess(context -> {
            // Set the pack name and description
            context.bedrockResourcePack().manifest().header().name(context.mod().name().trim() + " Resource Pack");
            context.bedrockResourcePack().manifest().header().description(context.mod().name().trim() + " " + context.mod().version() + " - Generated by " + Constants.MOD_NAME);

            // Generate the pack uuid from the mod file
            String packUuid = PackUtil.getModUUID(context.mod().roots()).toString();
            context.bedrockResourcePack().manifest().header().uuid(packUuid);

            // Generate module uuid based on type
            for (Modules module : context.bedrockResourcePack().manifest().modules()) {
                module.uuid(UUID.nameUUIDFromBytes((module.type + packUuid).getBytes()).toString());
            }

            // Copy the icon if it exists or copy the fallback icon
            try {
                if (context.mod().iconPath() != null) {
                    context.bedrockResourcePack().icon(Files.readAllBytes(context.mod().iconPath()));
                } else {
                    try (InputStream stream = MetadataPackModule.class.getClassLoader().getResourceAsStream("unknown.png")) {
                        context.bedrockResourcePack().icon(stream.readAllBytes());
                    }
                }
            } catch (IOException ignored) {
            }
        });
    }

    @Override
    public boolean test(@NotNull PackPostProcessContext<MetadataPackModule> context) {
        return true;
    }
}
